package com.managermype.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.managermype.business.MessageBusiness;
import com.managermype.util.Constant;
import com.managermype.util.Error;
import com.managermype.util.Page;

@Controller
public class SecurityController extends BaseController {

	@Autowired
	private MessageBusiness messageBusiness;

	@RequestMapping(value = "/loginajax.action", method = {RequestMethod.GET})
	public @ResponseBody String loginAjax(@RequestParam(value = "error", required = false) String error, 
			HttpSession session) {
			StringBuilder builderMessage = new StringBuilder("ERROR:");
			AuthenticationException authEx = getLastAuthenticationException(session);
			if (authEx != null) {
				builderMessage.append(authEx.getMessage());
				clearLastAuthenticationException(session);
				return builderMessage.toString();
			}
			else{
				builderMessage.append(messageBusiness.getExternalDescriptionMessage(Error.GENERIC_ERROR.getErrorCode()));
				return builderMessage.toString();
			}
	}

	@RequestMapping(value = "/login.action", method = RequestMethod.GET)
	public String login(@RequestParam(value = "error", required = false) String error, ModelMap modelMap,
			HttpSession session) {
		if (isAuthenticated()) {
			return "redirect:/index.htm";
		} else {
			if (error != null) {
				AuthenticationException authEx = getLastAuthenticationException(session);
				if (authEx != null) {
					modelMap.addAttribute(Constant.ERROR_MESSAGE, authEx.getMessage());
					clearLastAuthenticationException(session);
				}
			}
			return Page.LOGIN_PAGE.getJspPath();
		}
	}

	@RequestMapping(value = "/404NotFound.htm", method = RequestMethod.GET)
	public String notFound(ModelMap modelMap) {
		modelMap.addAttribute(Constant.ERROR_MESSAGE, "No se encuentra la página...");
		return Page.CONTROLLER_EXCEPTION_PAGE.getJspPath();
	}

	@RequestMapping(value = "/unauthorized.htm", method = RequestMethod.GET)
	public String restrictedAccess(HttpSession session) {
		return Page.ACCESS_DENIED_PAGE.getJspPath();
	}

	@RequestMapping(value = "/login.htm", method = RequestMethod.GET)
	public String goLogin(HttpSession session) {
		if (isAuthenticated()) {
			return "redirect:/index.htm";
		} else {
			return Page.LOGIN_PAGE.getJspPath();
		}
	}

}